# coding = utf-8
from selenium import webdriver  # 导入火狐浏览器的驱动
import time
import datetime

times = '2022-06-21 21:34:00'   # 秒杀时间
chrome_driver = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'   # 谷歌驱动放的位置
# webdriver = webdriver.Firefox()     # 打开一个火狐浏览器
webdriver = webdriver.Chrome(executable_path = chrome_driver)   # 打开一个chrome浏览器
webdriver.maximize_window()

def buy_on_time(buytime):
    while True:
        now = datetime.datetime.now()  # 获取电脑现在时间
        if now.strftime('%Y-%m-%d %H:%M:%S') == buytime:
            for i in range(1, 21):#每隔0.2秒抢购一次，尝试抢购20次
                webdriver.find_element_by_class_name("submit-btn")
                webdriver.find_element_by_id("order-submit").click()
                print(now.strftime('%Y-%m-%d %H:%M:%S'))
                print("第%d次抢购" % i)
                time.sleep(0.2)
            time.sleep(3)
            print('purchase success')
        time.sleep(0.5)

webdriver.get("https://www.jd.com")
time.sleep(1)
webdriver.find_element_by_link_text("你好，请登录").click()
print(f"请登录")
time.sleep(1)
webdriver.find_element_by_link_text("QQ").click()
time.sleep(3)
# webdriver.find_element_by_css_selector('#nick_1165589147').click()  #    错误  获取XPATH，F12，找到具体的位置，右键copy，Xpath
# webdriver.find_element_by_css_selector('img_out_focus').click() #使用CSS相对路径定位，点击账号密码登录
# time.sleep(1)
# webdriver.find_element_by_link_text("我的购物车").click() # 购物车方式1
webdriver.get("http://cart.jd.com/cart_index")    # 购物车方式2
time.sleep(1)

# 是否全选购物车
while 1 == 1:
    if webdriver.find_element_by_xpath('//*[@id="cart-body"]/div[2]/div[4]/div[1]/div/input'):
        webdriver.find_element_by_xpath('//*[@id="cart-body"]/div[2]/div[4]/div[1]/div/input').click()
        break

while 1 == 1 :
    # 获取电脑现在的时间
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(now)

    # 点击结算按钮
    if now > times :
        while 1 == 1 :
            try:
                if webdriver.find_element_by_link_text("去结算"):
                    print("here")
                    webdriver.find_element_by_link_text("去结算").click()
                    break
            except:
                pass
    # 点击提交订单按钮
    time.sleep(1)
    webdriver.find_element_by_link_text('提交订单')
    time.sleep(1)
    webdriver.find_element_by_link_text('立即支付')
    break

# webdriver.find_element_by_class_name("login-btn").click() # 一般需要登录，此处点击的是去登录按钮
# time.sleep(50)  # 为了避免输入校验码绕过了输入登录账户密码的步骤，此处打开的是二维码页面，请在50秒内用手机app扫描登录。
# buy_on_time("2020-05-22 00:00:00")#开始抢购时间
